<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="left" class="form-container">

      <sticky :z-index="10" :class-name="'sub-navbar '+postForm.status">
        <!-- <CommentDropdown v-model="postForm.comment_disabled" />
        <PlatformDropdown v-model="postForm.platforms" />
        <SourceUrlDropdown v-model="postForm.source_uri" /> -->
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          保存
        </el-button>
        <el-button v-loading="loading" type="warning" @click="draftForm">
          草稿
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row :gutter="20">
          <el-col :span="22">
            <el-form-item style="margin-bottom: 30px;" prop="name">
              <MDinput v-model="postForm.name" :maxlength="100" name="name" required>
                商品名称
              </MDinput>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label-width="60px" label="货号:" prop="sn" class="postInfo-container-item">
              <el-input v-model="postForm.sn"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分类" label-width="60px">
              <el-cascader v-model="postForm.categoryId" :options="categories" :props="cascaderProps" clearable placeholder="请选择"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="品牌" label-width="60px">
              <el-select v-model="postForm.brandId" class="filter-item" clearable placeholder="请选择">
                <el-option v-for="item in brands" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label-width="60px" label="原价:" prop="price" class="postInfo-container-item">
              <el-input-number v-model="postForm.price" :precision="2" :step="1.0" size="medium"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="60px" label="销售价:" prop="current_price" class="postInfo-container-item">
              <el-input-number v-model="postForm.current_price" :precision="2" :step="1.0" size="medium"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="60px" label="库存:" prop="stock" class="postInfo-container-item">
              <el-input-number v-model="postForm.stock" :step="1" size="medium"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">

          <el-col :span="8">
            <el-form-item label-width="60px" label="重量:" prop="weight" class="postInfo-container-item">
              <el-input-number v-model="postForm.weight" :step="1" size="medium"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="60px" label="体积:" prop="volume" class="postInfo-container-item">
              <el-input-number v-model="postForm.volume" :step="1" size="medium"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" label-width="60px" prop="status">
              <el-select v-model="postForm.status" class="filter-item" placeholder="请选择">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品图片" >
          <el-upload :limit="imgUploadLimit" :action="imgUploadUrl"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleUploadRemove" :on-success="handleUploadSuccess" :on-exceed="handleUploadExceed" :on-error="handleUploadError" >
            <i class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">1、第1个图片做为商品主图。2、只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          <el-dialog :visible.sync="uploadDialogVisible">
            <img width="100%" :src="uploadDialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item  prop="desc" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="postForm.content" :height="300" menubar=""/>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item style="margin-bottom: 40px;" label="SEO关键字:" prop="seo_keywords">
              <el-input v-model="postForm.seo_keywords" :rows="1" type="textarea" class="goods-textarea" autosize
                placeholder="请输入seo关键字" />
              <!-- <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}words</span> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item style="margin-bottom: 40px;" label="SEO描述:" prop="seo_description">
              <el-input v-model="postForm.seo_description" :rows="1" type="textarea" class="goods-textarea" autosize
                placeholder="请输入seo描述" />
              <!-- <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}words</span> -->
            </el-form-item>
          </el-col>

        </el-row>
        <!-- <Warning /> -->
        <!-- <el-form-item style="margin-bottom: 20px;" label="商品名称:"  prop="name">
         <el-input v-model="postForm.name"></el-input>
        </el-form-item>
        <div class="postInfo-container">
          <el-row>
            <el-form-item label-width="60px" label="货号:" class="postInfo-container-item">
              <el-input v-model="postForm.name"></el-input>
            </el-form-item>

            <el-col :span="10">
              <el-form-item label-width="120px" label="原价:" class="postInfo-container-item">
                <el-input-number v-model="postForm.price" :precision="2" :step="0.1" :max="10"></el-input-number>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label-width="90px" label="Importance:" class="postInfo-container-item">
                <el-rate v-model="postForm.importance" :max="3" :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                  :low-threshold="1" :high-threshold="3" style="display:inline-block" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="Summary:">
          <el-input v-model="postForm.content_short" :rows="1" type="textarea" class="goods-textarea" autosize
            placeholder="Please enter the content" />
          <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}words</span>
        </el-form-item>

        <el-form-item prop="content" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="postForm.content" :height="400" />
        </el-form-item>

        <el-form-item prop="image_uri" style="margin-bottom: 30px;">
          <Upload v-model="postForm.image_uri" />
        </el-form-item> -->
      </div>
    </el-form>
  </div>
</template>

<script>
  import Tinymce from '@/components/Tinymce'
  import Upload from '@/components/Upload/SingleImage3'
  import MDinput from '@/components/MDinput'
  import Sticky from '@/components/Sticky' // 粘性header组件
  import {validURL} from '@/utils/validate'
  import API from '@/api/goods'
  import brandAPI from '@/api/brand'
  import categoryAPI from '@/api/category'
  import imageAPI from '@/api/image'
  const defaultForm = {
    status: 1,
    name: '',
    sn: '',
    price: 0,
    current_price: 0,
    stock: 0,
    weight: 0,
    volume: 0,
    brand: null,
    brandId:null,
    category: null,
    categoryId: null,
    main_photo: null,
    photos:[],
    content: '',
    seo_keywords: '',
    seo_description: '',
    id: undefined,
    platforms: ['a-platform'],
    comment_disabled: false,
    importance: 0
  }

  export default {
    name: 'goodsDetail',
    components: {
      Tinymce,
      MDinput,
      Upload,
      Sticky
    },
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      const validateRequire = (rule, value, callback) => {
        if (value === '') {
          this.$message({
            message: rule.label + '为必传项',
            type: 'error'
          })
          callback(new Error(rule.label + '为必传项'))
        } else {
          callback()
        }
      }

      return {
        postForm: Object.assign({}, defaultForm),
        loading: false,
        brands: [],
        categories: [],
        cascaderProps: {value: 'id',label:'name',children:'childs',emitPath:false},
        uploadDialogImageUrl: '',
        uploadDialogVisible: false,
        imgUploadLimit:5,
        imgUploadUrl:"https://localhost:5001/api/imgupload",
        statusOptions: [{
          label: "上架",
          value: 1
        }, {
          label: "仓库",
          value: 2
        }, {
          label: "下架",
          value: 3
        }, {
          label: "违规下架",
          value: 4
        }],
        rules: {
          name: [{
            validator: validateRequire,
            label: '商品名称'
          }],
          sn: [{
            validator: validateRequire,
            label: '货号'
          }]
        },
        tempRoute: {}
      }
    },
    computed: {
      contentShortLength() {
        return this.postForm.content_short.length
      },
      displayTime: {
        // set and get is useful when the data
        // returned by the back end api is different from the front end
        // back end return => "2013-06-25 06:59:25"
        // front end need timestamp => 1372114765000
        get() {
          return (+new Date(this.postForm.display_time))
        },
        set(val) {
          this.postForm.display_time = new Date(val)
        }
      }
    },
    created() {
      this.getBrands()
      this.getCategories()
      const id = this.$route.query && this.$route.query.id
      id&& this.fetchOne(id);
      // Why need to make a copy of this.$route here?
      // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
      // https://github.com/PanJiaChen/vue-element-admin/issues/1221
      this.tempRoute = Object.assign({}, this.$route)
    },
    methods: {
      fetchOne(id) {
        API.fetchOne(id).then(response => {
          this.postForm = response.data
          // set tagsview title
          this.setTagsViewTitle()
          // set page title
          this.setPageTitle()
        }).catch(err => {
          console.log(err)
        })
      },
      setTagsViewTitle() {
        const title = '商品修改'
        const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.name}` })
        this.$store.dispatch('tagsView/updateVisitedView', route)
      },
      setPageTitle() {
        const title = '商品修改'
        document.title = `${title} - ${this.postForm.name}`
      },
      submitForm() {
        console.log(this.postForm)
        this.$refs.postForm.validate(valid => {
          if (valid) {
            this.loading = true
            this.postForm.main_photo=this.postForm.photos[0]  //商品主图为第一个
            if(this.postForm.id){ //id存在表示修改
              API.update(this.postForm).then(() => {
                this.$notify({
                  title: '提交成功',
                  message: '修改商品成功',
                  type: 'success',
                  duration: 1000
                })
              })
            }else{
                API.add(this.postForm).then(() => {
                  this.$notify({
                    title: '提交成功',
                    message: '发布商品成功',
                    type: 'success',
                    duration: 1000
                   })
                })
            }
            this.$router.push({path:'/admin/goods'})
            this.loading = false
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      draftForm() {
        if (this.postForm.content.length === 0 || this.postForm.title.length === 0) {
          this.$message({
            message: '请填写必要的标题和内容',
            type: 'warning'
          })
          return
        }
        this.$message({
          message: '保存成功',
          type: 'success',
          showClose: true,
          duration: 1000
        })
        this.postForm.status = 'draft'
      },
      getBrands() {
        brandAPI.fetchList().then(response => {
          if (!response.data.items) return
          this.brands = response.data.items;
        })
      },
      getCategories() {
        categoryAPI.fetchList().then(response => {
          if (!response.data.items) return
          this.categories = response.data.items;
        })
      },
      handleUploadRemove(file, fileList) {
         //console.log(file, fileList);
         imageAPI.delete(file.id) 
         this.postForm.photos=fileList.map((e,idx)=>{
            return e.response.data.path;
         })
      },
      handleUploadSuccess(response, file, fileList) {
         //console.log(file, fileList);
         if(!response.status){
            this.$message.error(response.msg);
            fileList.pop()
            return
         }
         file.id=response.data.id
         this.postForm.photos=fileList.map((e,idx)=>{
            return e.response.data.path;
         })
      },
      handlePictureCardPreview(file) {
        this.uploadDialogImageUrl = file.url;
        this.uploadDialogVisible = true;
      },
      handleUploadExceed(files, fileList){
        this.$message.warning(`当前限制选择 ${this.imgUploadLimit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      handleUploadError(err, file, fileList){
         this.$message.error(`上传文件${file.name}失败`);
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import "~@/styles/mixin.scss";

  .createPost-container {
    position: relative;

    .createPost-main-container {
      padding: 40px 45px 20px 50px;

      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;

        .postInfo-container-item {
          float: left;
        }
      }
    }

    .word-counter {
      width: 40px;
      position: absolute;
      right: 10px;
      top: 0px;
    }
  }

  .goods-textarea /deep/ {
    textarea {
      padding-right: 40px;
      resize: none;
      border: none;
      border-radius: 0px;
      border-bottom: 1px solid #bfcbd9;
    }
  }
</style>
